import { Injectable, BadRequestException } from '@nestjs/common';
import { createWriteStream } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class FileUploadService {
  private readonly uploadsDir = join(__dirname, '..', '..', 'uploads');

  /**
   * 上传单个文件
   * @param file - 要上传的文件
   * @returns 包含文件路径的对象
   */
  async uploadFile(file: Express.Multer.File): Promise<{ path: string }> {
    if (!file) {
      throw new BadRequestException('没有文件被上传');
    }

    // 检查文件类型是否为图片
    if (!file.mimetype.startsWith('image/')) {
      throw new BadRequestException('只能上传图片文件');
    }

    // 生成唯一文件名
    const filename = `${uuidv4()}-${file.originalname}`;
    const filepath = join(this.uploadsDir, filename);

    // 保存文件
    await new Promise<void>((resolve, reject) => {
      const writeStream = createWriteStream(filepath);
      writeStream.write(file.buffer);
      writeStream.end();
      writeStream.on('finish', resolve);
      writeStream.on('error', reject);
    });

    // 返回可访问的文件路径
    return { path: `/uploads/${filename}` };
  }

  /**
   * 上传多个文件
   * @param files - 要上传的文件数组
   * @returns 包含所有文件路径的数组
   */
  async uploadMultipleFiles(files: Express.Multer.File[]): Promise<{ path: string }[]> {
    if (!files || files.length === 0) {
      throw new BadRequestException('没有文件被上传');
    }

    return Promise.all(files.map(file => this.uploadFile(file)));
  }
}